/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.generator.coreGenerator.base.accessorgen.method;

import com.inspur.edp.caf.generator.baseInfo.ParameterInfo;
import com.inspur.edp.caf.generator.baseInfo.TypeInfo;
import com.inspur.edp.caf.generator.method.ClassMethodGenerator;
import com.inspur.edp.cef.entity.accessor.entity.IEntityAccessor;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.gencommon.MediateType;
import java.util.ArrayList;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.EnhancedForStatement;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.InfixExpression;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.ParenthesizedExpression;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;

//    
//     private void initialize(IEntityAccessor belongEntity)
//        {
//            if (((IYCompany)belongEntity).Items == null)
//                return;
//            foreach (var item in ((IYCompany)belongEntity).Items)
//            {
//                var accessor = new YCompanyItemAccessor(item);
//                base.InnerAdd(accessor);
//            }
//        }        
//     
public class AccessorCollectionInitGenerator extends ClassMethodGenerator
{
	private MediateType parentDataType;
	private String collectionPropName;
	private MediateType childAccessorType;
	private MediateType childDataType;

	public AccessorCollectionInitGenerator(MediateType parentDataType, String collectionPropName
			, MediateType childAccessorType, MediateType childDataType)
	{
		this.parentDataType = parentDataType;
		this.collectionPropName = collectionPropName;
		this.childAccessorType = childAccessorType;
		this.childDataType = childDataType;
	}

	@Override
	protected Block buildMethodBody() {
		Block block=ast.newBlock();
		IfStatement ifStatement=ast.newIfStatement();
		addIfExpression(ifStatement);
		addIfThen(ifStatement);

		block.statements().add(ifStatement);
		return block;
	}

	private void addIfExpression(IfStatement ifStatement) {
		InfixExpression infixExpression=ast.newInfixExpression();
		infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_AND);

		InfixExpression infixExpressionLeft=ast.newInfixExpression();
		infixExpressionLeft.setOperator(InfixExpression.Operator.NOT_EQUALS);
		infixExpressionLeft.setLeftOperand(ast.newSimpleName(VarName));
		infixExpressionLeft.setRightOperand(ast.newNullLiteral());
		infixExpression.setLeftOperand(infixExpressionLeft);


		InfixExpression infixExpressionRight=ast.newInfixExpression();
		infixExpressionRight.setOperator(InfixExpression.Operator.NOT_EQUALS);
		infixExpressionRight.setRightOperand(ast.newNullLiteral());

		MethodInvocation methodInvocation=ast.newMethodInvocation();
		methodInvocation.setName(ast.newSimpleName("get"+collectionPropName));

		MethodInvocation methodInvocationExpression=ast.newMethodInvocation();
		methodInvocationExpression.setExpression(ast.newSimpleName(VarName));
		methodInvocationExpression.setName(ast.newSimpleName("getInnerData"));
		CastExpression castExpression = ast.newCastExpression();
		castExpression.setExpression(methodInvocationExpression);
		castExpression.setType(ast.newSimpleType(ast.newName(parentDataType.getFullName())));
		ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
		parenthesizedExpression.setExpression(castExpression);
		methodInvocation.setExpression(parenthesizedExpression);

		infixExpressionRight.setLeftOperand(methodInvocation);
		infixExpression.setRightOperand(infixExpressionRight);



		ifStatement.setExpression(infixExpression);
	}

	private void addIfThen(IfStatement ifStatement)
	{
		Block block=ast.newBlock();
		EnhancedForStatement forStatement=ast.newEnhancedForStatement();

		addIfThenForParameter(forStatement);
		addIfThenForExpress(forStatement);
		addIfThenForBody(forStatement);

		block.statements().add(forStatement);
		ifStatement.setThenStatement(block);
	}

	private void addIfThenForBody(EnhancedForStatement forStatement)
	{
		Block block=ast.newBlock();
		addIfThenForBodyVarDeclaration(block);
		addIfThenForBodyInnerAdd(block);

		forStatement.setBody(block);
	}

	private void addIfThenForBodyVarDeclaration(Block block) {
		VariableDeclarationFragment variableDeclarationFragment=ast.newVariableDeclarationFragment();
		variableDeclarationFragment.setName(ast.newSimpleName("accessor"));

		ClassInstanceCreation classInstanceCreation=ast.newClassInstanceCreation();
		classInstanceCreation.setType(ast.newSimpleType(ast.newName(childAccessorType.getFullName())));
		CastExpression castDataExpr = ast.newCastExpression();
		castDataExpr.setType(ast.newSimpleType(ast.newName(childDataType.getFullName())));
		castDataExpr.setExpression(ast.newSimpleName("item"));
		classInstanceCreation.arguments().add(castDataExpr);
		variableDeclarationFragment.setInitializer(classInstanceCreation);

		VariableDeclarationStatement variableDeclarationStatement=ast.newVariableDeclarationStatement(variableDeclarationFragment);
		variableDeclarationStatement.setType(ast.newSimpleType(ast.newName(childAccessorType.getFullName())));
		block.statements().add(variableDeclarationStatement);
	}

	private void addIfThenForBodyInnerAdd(Block block) {
		MethodInvocation methodInvocation=ast.newMethodInvocation();
		methodInvocation.setExpression(ast.newThisExpression());
		methodInvocation.setName(ast.newSimpleName("innerAdd"));
		methodInvocation.arguments().add(ast.newSimpleName("accessor"));
		ExpressionStatement expressionStatement=ast.newExpressionStatement(methodInvocation);
		block.statements().add(expressionStatement);
	}

	private void addIfThenForExpress(EnhancedForStatement forStatement)
	{
		MethodInvocation methodInvocation=ast.newMethodInvocation();
		MethodInvocation methodInvocation1=ast.newMethodInvocation();
		methodInvocation1.setExpression(ast.newSimpleName(VarName));
		methodInvocation1.setName(ast.newSimpleName("getInnerData"));

		CastExpression castExpression = ast.newCastExpression();
		castExpression.setExpression(methodInvocation1);
		castExpression.setType(ast.newSimpleType(ast.newName(parentDataType.getFullName())));
		ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
		parenthesizedExpression.setExpression(castExpression);

		methodInvocation.setExpression(parenthesizedExpression);
		methodInvocation.setName(ast.newSimpleName("get"+collectionPropName));
		forStatement.setExpression(methodInvocation);
	}

	private void addIfThenForParameter(EnhancedForStatement ifStatement)
	{
		SingleVariableDeclaration singleVariableDeclaration=ast.newSingleVariableDeclaration();
		singleVariableDeclaration.setName(ast.newSimpleName("item"));
		singleVariableDeclaration.setType(new TypeInfo(IEntityData.class).getType(ast));
		ifStatement.setParameter(singleVariableDeclaration);
	}

//	@Override
//	protected Block buildMethodBody()
//	{
//		return SyntaxFactory.Block(SyntaxFactory.IfStatement
//				(SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.IdentifierName(VarName),
//						SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)), SyntaxFactory.ReturnStatement()),
//				SyntaxFactory.IfStatement(SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression,
//						SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
//								SyntaxFactory.ParenthesizedExpression(SyntaxFactory.CastExpression(TypeUtils.getTypeSyntax(parentDataType),
//										SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName(VarName),
//												SyntaxFactory.IdentifierName("InnerData")))), SyntaxFactory.IdentifierName(collectionPropName)),
//						SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)), SyntaxFactory.ReturnStatement()), SyntaxFactory.ForEachStatement(TypeUtils.getTypeSyntax(childDataType), SyntaxFactory.Identifier("item"), SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParenthesizedExpression(SyntaxFactory.CastExpression(TypeUtils.getTypeSyntax(parentDataType), SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName(VarName), SyntaxFactory.IdentifierName("InnerData")))), SyntaxFactory.IdentifierName(collectionPropName)), SyntaxFactory.Block(SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName("var")).WithVariables(SyntaxFactory.<VariableDeclaratorSyntax>SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier("accessor")).WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.ObjectCreationExpression(SyntaxFactory.IdentifierName(childAccessorType.getName())).WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.<ArgumentSyntax>SingletonSeparatedList(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("item")))))))))), SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.BaseExpression(), SyntaxFactory.IdentifierName("InnerAdd"))).WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.<ArgumentSyntax>SingletonSeparatedList(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("accessor")))))))));
//	}

	public static final String methodName = "initialize";
	@Override
	protected String getMethodName()
	{
		return methodName;
	}


	@Override
	protected TypeInfo getReturnType() {
		return new TypeInfo(void.class.getTypeName());
	}


	@Override
	protected ArrayList<Modifier.ModifierKeyword> getAccessModifiers() {
		ArrayList<Modifier.ModifierKeyword> list =new ArrayList<>();
		list.add(Modifier.ModifierKeyword.PRIVATE_KEYWORD);
		return list;
	}

	private static final String VarName = "belongEntity";
	@Override
	protected ArrayList<ParameterInfo> getParameterCollection() {
		ArrayList<ParameterInfo> list =new ArrayList<>();
		ParameterInfo parameterInfo=new ParameterInfo();
		parameterInfo.setParamName(VarName);
		parameterInfo.setParamType(new TypeInfo(IEntityAccessor.class.getTypeName()));
		list.add(parameterInfo);
		return list;
	}
}
